package com.ucap.spyxmp.controller;


import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.ucap.spyxmp.data.RestResultBuilder;
import com.ucap.spyxmp.data.ResultModel;
import com.ucap.spyxmp.data.SpjyxkzPdfModel;
import com.ucap.spyxmp.data.ZxjdsPdfModel;
import com.ucap.spyxmp.model.SpyxmpMailInfo;
import com.ucap.spyxmp.util.CommonUtil;
import com.ucap.spyxmp.util.LicensePdfUtil;
import com.ucap.util.Conts;
import com.ucap.util.DateTime;
import com.ucap.util.DateUtil;
import com.ucap.util.StringUtils;
import com.ucap.spyxmp.model.SpyxmpApplyItem;
import com.ucap.spyxmp.model.SpyxmpSpjyxkz;
import com.ucap.weixin.model.WxWsbsUser;
import com.ucap.wsbs.model.WxWsbsFile;
import com.ucap.wsbs.model.YwSgsxzgljKydjxx;
import com.ucap.wsbs.util.ConvertCodeUtil;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 食品经营许可证controller
 */
public class SpjyxkzController extends SpyxmpBaseController {

    private static String tableName = "SPYXMP_SPJYXKZ";
    public String retPath;

    @Before(Tx.class)
    public void save() throws Exception {

        SpyxmpApplyItem applyItem = this.getApplyItemCg();
        String sblsh = applyItem.getStr("SBLSH");
        System.out.println(sblsh);

        //保存申请主体信息
        applyItem.set("STATUS", "1");
        applyItem.set("MODIFYDATE", DateUtil.getCurrtentDateTime());
        applyItem.update();

        List<WxWsbsFile> wsbsFiles = WxWsbsFile.me.findFileListByTableNameAndUserId("SIGNATURE", this.getUserId());
        if (wsbsFiles.size() == 0) {
            throw new Exception("未获取到签名数据");
        }
        WxWsbsFile.me.updateSblsh(sblsh, "SIGNATURE", this.getUserId());

        //保存申请表信息
        switch (getType()) {
            case "1":
                this.saveBz(sblsh);
                break;
            case "2":
                this.saveZx(sblsh);
                break;
            case "3":
                this.saveBg(sblsh);
                break;
            default:
                this.saveXq(sblsh);
                break;
        }
        renderJson(RestResultBuilder.builder().success(applyItem).build());
    }

    /**
     * 续期数据保存
     *
     * @param sblsh
     * @throws Exception
     */
    @Before(Tx.class)
    private void saveXq(String sblsh) throws Exception {

        String spjyxkz = getPara("spjyxkzh");
        SpyxmpSpjyxkz data = new SpyxmpSpjyxkz();
        data.set("ID", StringUtils.getUUID());
        data.set("APPLYID", sblsh);
        data.set("TYPE", getType());
        data.set("SPJYXKZH", spjyxkz);
        data.set("LXR", getPara("lxr"));
        data.set("LXRDH", getPara("lxrdh"));
        data.set("REASON", getPara("reason"));
        data.set("ADDTIME", DateUtil.getCurrtentDateTime());
        data.set("MODIFYDATE", DateUtil.getCurrtentDateTime());

        SpjyxkzPdfModel pdfModel = this.saveLicense(sblsh, data, getType());
        data.set("JYZMC", pdfModel.getJyzmc());
        data.set("TYSHXYDM", pdfModel.getTyshxydm());
        data.set("FDDBR", pdfModel.getFddbr());
        data.set("JYCS", pdfModel.getJycs());
        data.set("ZTYTJTLB", pdfModel.getZtyt());
        data.set("JYXMJTLB", pdfModel.getJyxm());
        data.set("YXQX", pdfModel.getYxq());
        data.set("RCJDGLJG", pdfModel.getRcjdgljg());
        data.set("RCJDGLRY", pdfModel.getRcjdglry());
        data.set("QFR", pdfModel.getQfr());
        data.set("ZS", pdfModel.getZs());
        data.set("QFRQ", pdfModel.getQfrq());
        data.save();
    }

    /**
     * 变更数据保存
     *
     * @param sblsh
     * @throws Exception
     */
    @Before(Tx.class)
    private void saveBg(String sblsh) throws Exception {

        String spjyxkz = getPara("spjyxkzh");
        SpyxmpSpjyxkz data = new SpyxmpSpjyxkz();
        data.set("ID", StringUtils.getUUID());
        data.set("APPLYID", sblsh);
        data.set("TYPE", getType());
        data.set("SPJYXKZH", spjyxkz);
        /*

        if(getPara("spxsjyz") != null){
            data.set("ZTYTJTLB2", getPara("spxsjyz"));
        }else if(getPara("cyfwjyz") != null){
            data.set("ZTYTJTLB2", getPara("cyfwjyz"));
        }else{
            data.set("ZTYTJTLB2", getPara("dwst"));
        }*/


        //网络经营模块
        data.set("SFHWLJY", getPara("sfhwljy"));
        String[] wjjylxArray = getParaValues("wljylx");
        if (wjjylxArray != null && wjjylxArray.length > 0) {
            data.set("WLJYLX", StringUtils.join(wjjylxArray, ","));
        }
        data.set("ZJWZ", getPara("zjwz"));
        data.set("SFJYSTMD", getPara("sfjystmd"));
        data.set("LXR", getPara("lxr"));
        data.set("LXRDH", getPara("lxrdh"));
        data.set("ADDTIME", DateUtil.getCurrtentDateTime());
        data.set("MODIFYDATE", DateUtil.getCurrtentDateTime());

        SpjyxkzPdfModel pdfModel = this.saveLicense(sblsh, data, getType());
        data.set("JYZMC", pdfModel.getJyzmc());
        data.set("TYSHXYDM", pdfModel.getTyshxydm());
        data.set("FDDBR", pdfModel.getFddbr());
        data.set("JYCS", pdfModel.getJycs());
        data.set("ZTYTJTLB", pdfModel.getZtyt());
        data.set("JYXMJTLB", pdfModel.getJyxm());
        data.set("YXQX", pdfModel.getYxq());
        data.set("RCJDGLJG", pdfModel.getRcjdgljg());
        data.set("RCJDGLRY", pdfModel.getRcjdglry());
        data.set("QFR", pdfModel.getQfr());
        data.set("ZS", pdfModel.getZs());
        data.set("QFRQ", pdfModel.getQfrq());
        data.save();

    }

    /**
     * 补证数据保存 签发日期改为当前时间
     *
     * @param sblsh
     * @throws Exception
     */
    @Before(Tx.class)
    private void saveBz(String sblsh) throws Exception {

        List<WxWsbsFile> wsbsFiles = WxWsbsFile.me.findFileListByTableNameAndUserId(tableName, this.getUserId());
        if (wsbsFiles.size() == 0) {
            throw new Exception("请上传遗失证明");
        }
        WxWsbsFile.me.updateSblsh(sblsh, tableName, this.getUserId());

        String spjyxkz = getPara("spjyxkzh");
        SpyxmpSpjyxkz data = new SpyxmpSpjyxkz();
        data.set("ID", StringUtils.getUUID());
        data.set("APPLYID", sblsh);
        data.set("TYPE", getType());
        data.set("SPJYXKZH", spjyxkz);
        data.set("LXR", getPara("lxr"));
        data.set("LXRDH", getPara("lxrdh"));
        data.set("REASON", getPara("reason"));
        data.set("ADDTIME", DateUtil.getCurrtentDateTime());
        data.set("MODIFYDATE", DateUtil.getCurrtentDateTime());

        SpjyxkzPdfModel pdfModel = this.saveLicense(sblsh, data, getType());
        data.set("JYZMC", pdfModel.getJyzmc());
        data.set("TYSHXYDM", pdfModel.getTyshxydm());
        data.set("FDDBR", pdfModel.getFddbr());
        data.set("JYCS", pdfModel.getJycs());
        data.set("ZTYTJTLB", pdfModel.getZtyt());
        data.set("JYXMJTLB", pdfModel.getJyxm());
        data.set("YXQX", pdfModel.getYxq());
        data.set("RCJDGLJG", pdfModel.getRcjdgljg());
        data.set("RCJDGLRY", pdfModel.getRcjdglry());
        data.set("QFR", pdfModel.getQfr());
        data.set("ZS", pdfModel.getZs());
        data.set("QFRQ", pdfModel.getQfrq());

        data.save();
    }

    /**
     * 注销数据保存
     *
     * @param sblsh
     * @throws Exception
     */
    @Before(Tx.class)
    private void saveZx(String sblsh) throws Exception {
        WxWsbsUser user = Conts.getSessionUser(getSession());
        String sfjbyj = getPara("sfjbyj");
        if ("1".equals(sfjbyj)) {
            //具备原件，填写邮寄地址
            SpyxmpMailInfo mailInfo = null;
            List<SpyxmpMailInfo> mailInfos = SpyxmpMailInfo.me.findByUserId(getUserId());
            if (mailInfos.size() > 0) {
                mailInfo = mailInfos.get(0);
                mailInfo.set("NAME", getPara("yjr"));
                mailInfo.set("MOBILE", getPara("yjrdh"));
                mailInfo.set("ADDRESS", getPara("yjrdz"));
                mailInfo.set("MODIFYDATE", DateUtil.getCurrtentDateTime());
                mailInfo.update();
            } else {
                mailInfo = new SpyxmpMailInfo();
                mailInfo.set("ID", StringUtils.getUUID());
                mailInfo.set("USERID", getUserId());
                mailInfo.set("NAME", getPara("yjr"));
                mailInfo.set("MOBILE", getPara("yjrdh"));
                mailInfo.set("ADDRESS", getPara("yjrdz"));
                mailInfo.set("ADDTIME", DateUtil.getCurrtentDateTime());
                mailInfo.set("MODIFYDATE", DateUtil.getCurrtentDateTime());
                mailInfo.save();
            }
        } else {
            //上传遗失证明
            List<WxWsbsFile> wsbsFiles = WxWsbsFile.me.findFileListByTableNameAndUserId(tableName, this.getUserId());
            if (wsbsFiles.size() == 0) {
                throw new Exception("请上传遗失证明");
            }
            WxWsbsFile.me.updateSblsh(sblsh, tableName, this.getUserId());
        }

        SpyxmpSpjyxkz data = new SpyxmpSpjyxkz();
        data.set("ID", StringUtils.getUUID());
        data.set("APPLYID", sblsh);
        data.set("TYPE", getType());
        data.set("SPJYXKZH", getPara("spjyxkzh"));
        data.set("LXR", getPara("lxr"));
        data.set("LXRDH", getPara("lxrdh"));
        data.set("REASON", getPara("reason"));
        data.set("ADDTIME", DateUtil.getCurrtentDateTime());
        data.set("MODIFYDATE", DateUtil.getCurrtentDateTime());
        //添加邮寄信息
        data.set("SFJBYJ", sfjbyj);
        data.set("YJR", getPara("yjr"));
        data.set("YJRDH", getPara("yjrdh"));
        data.set("YJRDZ", getPara("yjrdz"));
        //获取证照信息
        if (getSession().getAttribute(CommonUtil.LICENSE_DATA) == null) {
            throw new Exception("没有获取到相关证件信息");
        }

        JSONObject xkzLicense = (JSONObject) getSession().getAttribute(CommonUtil.LICENSE_DATA);
        String jyzmc = xkzLicense.getString("经营者名称");
        Calendar nowCalendar = Calendar.getInstance();
        String name = jyzmc;
        String zi = "2018";
        String hao;
        String year = String.valueOf(nowCalendar.get(Calendar.YEAR));
        String month = String.valueOf(nowCalendar.get(Calendar.MONTH) + 1);
        String day = String.valueOf(nowCalendar.get(Calendar.DATE));

        int typeCodeInt = Integer.valueOf(getType());
        String typeCode = ConvertCodeUtil.getOrderCode(typeCodeInt);
        String datePrefix = new DateTime().getDateTimeNYR();
        StringBuffer sblshStb = new StringBuffer(datePrefix);
        sblshStb.append(getTableNameCode()).append(typeCode);
        int code = SpyxmpApplyItem.me.findLikeSblshData(sblshStb.toString()).size() + 1;
        String haoCode;
        if(code > 99){
            haoCode = "" + code;
        }else{
            haoCode = "0" + code;
        }
        hao = "18" + month + day + haoCode;

        ZxjdsPdfModel pdfModel = new ZxjdsPdfModel(name, zi, hao, year, month, day);
        //正本路径
        String zxjdsPath = LicensePdfUtil.generateSpjyxkzZxjds(pdfModel);

        try {

            WxWsbsFile licenseZb = new WxWsbsFile();
            licenseZb.set("ID", StringUtils.getUUID());
            licenseZb.set("SBLSH", sblsh);
            licenseZb.set("USERID", user.getStr("id"));
            licenseZb.set("FILEPATH", zxjdsPath);
            licenseZb.set("FILENAME", "注销决定书.png");
            licenseZb.set("CONTENTTYPE", "image/png");
            licenseZb.set("TABLENAME", "SPJYXKZ_ZXJDS");
            licenseZb.set("ADDTIME", new DateTime().getTimestamp());
            licenseZb.set("ADDUSER", user.get("id"));
            licenseZb.set("UPDATETIME", new DateTime().getTimestamp());
            licenseZb.set("UPDATEUSER", user.get("id"));
            licenseZb.set("DATASTATE", "I");

            boolean isZbSave = licenseZb.save();

            if (!isZbSave) {
                throw new Exception("保存注销决定书失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        data.set("JYZMC", xkzLicense.getString("经营者名称"));
        data.save();
        //发送消息
        this.sendTextMsg();
    }

    @Before(Tx.class)
    private SpjyxkzPdfModel saveLicense(String sblsh, SpyxmpSpjyxkz data, String type) throws Exception {
        WxWsbsUser user = Conts.getSessionUser(getSession());
        String spjyxkz = data.getStr("SPJYXKZH");
        //生成业务办理成功后的证照信息
        //获取证照信息
        if (getSession().getAttribute(CommonUtil.LICENSE_DATA) == null) {
            throw new Exception("没有获取到相关证件信息");
        }

        JSONObject xkzLicense = (JSONObject) getSession().getAttribute(CommonUtil.LICENSE_DATA);

        String jyzmc = xkzLicense.getString("经营者名称");
        String tyshxydm = xkzLicense.getString("社会信用代码（身份证号码）");
        String fddbr = xkzLicense.getString("法定代表人（负责人）");
        String zs = xkzLicense.getString("经营场所");
        String jycs = xkzLicense.getString("经营场所");
        String ztytlb = xkzLicense.getString("主体业态");
        String jyxm = xkzLicense.getString("经营项目");
        String yxqxNow = xkzLicense.getString("有效期至");
        String[] yxqxArray = yxqxNow.split("-");
        String yxqn = yxqxArray[0];
        String yxqy = yxqxArray[1];
        String yxqr = yxqxArray[2];
        String rcjdgljg = xkzLicense.getString("日常监督管理机构") != null ? xkzLicense.getString("日常监督管理机构") : "无";
        String rcjdglry = xkzLicense.getString("日常监督管理人员") != null ? xkzLicense.getString("日常监督管理人员") : "无";
        String fzjg = xkzLicense.getString("发证机关") != null ? xkzLicense.getString("发证机关") : "东莞市食品药品监督管理局";
        String qfr = xkzLicense.getString("签发人") != null ? xkzLicense.getString("签发人") : "无";

        Calendar nowCalendar = Calendar.getInstance();
        String qfrqN = xkzLicense.getString("有效期始");
        String[] qfrqArray = qfrqN.split("-");
        String qfrqn = qfrqArray[0];
        String qfrqy = qfrqArray[1];
        String qfrqr = qfrqArray[2];


        switch (type) {
            case "1": //补发 签发日期改为现在

                qfrqn = String.valueOf(nowCalendar.get(Calendar.YEAR));
                qfrqy = String.valueOf(nowCalendar.get(Calendar.MONTH) + 1);
                qfrqr = String.valueOf(nowCalendar.get(Calendar.DATE));
                break;
            case "3": //变更

                if(!ztytlb.contains("网络经营")){
                    ztytlb = ztytlb + "（网络经营）";
                }


                break;
            default:  //续期 当前有效期限+5年，签发日期改为当前

                qfrqn = String.valueOf(nowCalendar.get(Calendar.YEAR));
                qfrqy = String.valueOf(nowCalendar.get(Calendar.MONTH) + 1);
                qfrqr = String.valueOf(nowCalendar.get(Calendar.DATE));

                yxqn = String.valueOf(Integer.valueOf(yxqn) + 5);

                break;
        }


        SpjyxkzPdfModel pdfModel = new SpjyxkzPdfModel(jyzmc, tyshxydm
                , fddbr, zs, jycs, ztytlb, jyxm, yxqn, yxqy, yxqr, spjyxkz, rcjdgljg
                , rcjdglry, fzjg, qfr, qfrqn, qfrqy, qfrqr);
        //正本路径
        String licenseZbPath = LicensePdfUtil.generateSpjyxkzZb(pdfModel);
        //副本路径
        String licenseFbPath = LicensePdfUtil.generateSpjyxkzFb(pdfModel);

        try {

            WxWsbsFile licenseZb = new WxWsbsFile();
            licenseZb.set("ID", StringUtils.getUUID());
            licenseZb.set("SBLSH", sblsh);
            licenseZb.set("USERID", user.getStr("id"));
            licenseZb.set("FILEPATH", licenseZbPath);
            licenseZb.set("FILENAME", "食品经营许可证正本.png");
            licenseZb.set("CONTENTTYPE", "image/png");
            licenseZb.set("TABLENAME", "SPJYXKZ_ZB");
            licenseZb.set("ADDTIME", new DateTime().getTimestamp());
            licenseZb.set("ADDUSER", user.get("id"));
            licenseZb.set("UPDATETIME", new DateTime().getTimestamp());
            licenseZb.set("UPDATEUSER", user.get("id"));
            licenseZb.set("DATASTATE", "I");

            boolean isZbSave = licenseZb.save();

            if (!isZbSave) {
                throw new Exception("保存食品经营许可证正本失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


        try {

            WxWsbsFile licenseFb = new WxWsbsFile();
            licenseFb.set("ID", StringUtils.getUUID());
            licenseFb.set("SBLSH", sblsh);
            licenseFb.set("USERID", user.getStr("id"));
            licenseFb.set("FILEPATH", licenseFbPath);
            licenseFb.set("FILENAME", "食品经营许可证副本.png");
            licenseFb.set("CONTENTTYPE", "image/png");
            licenseFb.set("TABLENAME", "SPJYXKZ_FB");
            licenseFb.set("ADDTIME", new DateTime().getTimestamp());
            licenseFb.set("ADDUSER", user.get("id"));
            licenseFb.set("UPDATETIME", new DateTime().getTimestamp());
            licenseFb.set("UPDATEUSER", user.get("id"));
            licenseFb.set("DATASTATE", "I");

            boolean isFbSave = licenseFb.save();

            if (!isFbSave) {
                throw new Exception("保存食品经营许可证副本失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return pdfModel;
    }

    public void getData() {

    }

    public SpjyxkzController() {
        super(tableName);
    }
}
